import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'utils/jsbridge.dart';
import 'register.dart';
import 'jsmethod.dart';

class WebViewPage extends StatefulWidget {
  const WebViewPage({super.key});

  @override
  State<StatefulWidget> createState() => _WebViewPage();
}

class _WebViewPage extends State<StatefulWidget> {
  String locationStr = '';
  String title = 'WebView';

  final InAppWebJSHandlerManager _inAppWebJSHandlerManager =
      InAppWebJSHandlerManager();

  late InAppWebJSBridgeRegister _inAppWebJSBridgeRegister;

  InAppWebViewController? webViewController;
  final GlobalKey webViewKey = GlobalKey();

  final String userAgent = 'MyApp/1.0';

  @override
  void initState() {
    super.initState();
    _inAppWebJSBridgeRegister =
        InAppWebJSBridgeRegister(_inAppWebJSHandlerManager);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
          title: Text(title),
        ),
        body: InAppWebView(
          key: webViewKey,
          initialUrlRequest: URLRequest(url: Uri.parse('http://120.24.44.3')),
          initialOptions: InAppWebViewGroupOptions(
            crossPlatform: InAppWebViewOptions(
              userAgent: userAgent,
            ),
          ),
          onWebViewCreated: (controller) async {
            webViewController = controller;
            _inAppWebJSHandlerManager.updateController(
              context: context,
              inAppWebViewController: webViewController,
            );
            _inAppWebJSHandlerManager.injectJavascriptReady();
            _inAppWebJSBridgeRegister.registerHandlers(
                jsChannelRegisterHandler: (handleName, data) {
              if (handleName == JSChannelRegisterMethod.setTitle) {
                setState(() {
                  title = data;
                });
              }
            });
          },
          onTitleChanged: (controller, t) {
            setState(() {
              title = t ?? "";
            });
          },
          onLoadStop: (controller, url) {
            // 注入
            _inAppWebJSHandlerManager.injectBridgeJavascript();

            _inAppWebJSHandlerManager.checkJavascriptBridge();
          },
        ));
  }
}
